package com.tarena.lbs.basic.web.repository.impl;

import com.github.pagehelper.PageInfo;

import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.mapper.AdminMapper;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.common.basic.converter.AdminConverter;
import com.tarena.lbs.common.passport.utils.MD5Util;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.dos.AdminDO;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class AdminRepositoryImpl implements AdminRepository {

    private static final String  INITIAL_PASSWORD="123456";

    @Resource
    private AdminMapper adminMapper;

    @Autowired
    private AdminConverter adminConverter;


    @Override public int insert(AdminParam param) {
        /*UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (loginUser != null) {
            param.setBusinessId(loginUser.getId());
        }*/
        //businessId就应该是店铺iD
        AdminDO adminDO = adminConverter.param2DO(param);
        adminDO.setBusinessId(param.getBusinessId());
        adminDO.setCreateTime(new Date());
        String password = MD5Util.getMd5(adminDO.getAccountPassword());
        adminDO.setAccountPassword(password);
        int row = adminMapper.insert(adminDO);
        return row;
    }

    @Override public int deleteById(Integer id) {
        return adminMapper.deleteById(id);
    }

    @Override public int resetPasswordById(Integer id) {
        String password = MD5Util.getMd5(INITIAL_PASSWORD);
        return adminMapper.resetPasswordById(id,password);
    }

    @Override
    public AdminBO getAdminById(Integer id) {
        return adminConverter.do2bo(adminMapper.selectByPrimaryKey(id));
    }

    @Override public int assignRoles(Integer id, Integer accountType) {
        return adminMapper.assignRoles(id,accountType);
    }

    @Override
    public BasePageList<AdminBO> userList(AdminQuery query) {
        int page = query.getPageNo();
        int pageSize = query.getPageSize();
        List<AdminDO> list = adminMapper.selectList(query);
        PageInfo<AdminDO> pageInfo = new PageInfo<>(list);
        List<AdminBO> boList = pageInfo.getList().stream().map(adminDo -> {
            AdminBO adminBO = new AdminBO();
            BeanUtils.copyProperties(adminDo, adminBO);
            return adminBO;
        }).collect(Collectors.toList());
        return new BasePageList<AdminBO>(boList,Long.valueOf(pageInfo.getTotal()));
    }
}
